const util = require("../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    count: 0,
    progress: 0,
    isSubmit: false,
    ans: [],
    quesName: "",
    checked: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.quesName = options.quesName;

    // 页面加载时开始请求数据
    this.query(options)
      .then(this.codeData.bind(this));
  },

  // 发送请求
  query(options) {
    return new Promise(resolve => {
      wx.request({
        url: 'http://47.107.121.61/user/ques',
        data: {
          quesName: this.data.quesName
        },
        method: "GET",
        header: {
          'content-type': 'application/json'
        },
        success: res => {
          const status = res.data.status;
          const data = res.data.data;
          resolve(data);
        }
      })
    })
  },

  // 处理返回数据
  codeData(data) {
    let quesData = data[0].quesContent;
    let quesName = data[0].quesName;
    let length = quesData.length;
    let gist = data[0].quesGist;
    let quesGist = [];
    for (let item in gist) {
      quesGist.push({
        score: gist[item].slice(0, 1),
        desc: gist[item].slice(1)
      })
    }

    this.setData({ 
      quesData,
      quesName,
      length,
      quesGist
    })
  },

  // 进度条
  radioChange: function (e) {
    let offsetTop = e.target.offsetTop;
    let checked = this.data.checked;
    if (checked.indexOf(offsetTop) !== -1) return;
    checked.push(offsetTop);
    let data = this.data;
    let count = data.count;
    let length = data.length;
    let progress = data.progress;
    count += 1;
    if (count !== length) {
      progress = Math.round(count * 100 / length);
    }else {
      progress = 100;
    }
    this.setData({
      count,
      progress,
      checked
    })
  },

  // 表单提交
  formSubmit: function (e) {
    let ans = e.detail.value;
    let test = false;
    let length = this.data.length;
    console.log('form发生了submit事件，携带数据为：', ans);
    
    for (let item in ans) {
      if (ans[item] === "") {
        test = true;
        break;
      }
    }
    if (test == true) {
      util.alertView("提示", "有漏题，请仔细检查哦", () => {})
    }else {
      this.setData({
        warn: "",
        isSubmit: true,
        ans
      })
      wx.navigateTo({
        url: `/pages/quesAns/quesAns?quesName=${this.data.quesName}&ans=${JSON.stringify(this.data.ans)}`
      })
    }
  },

  formReset() {
    console.log('form发生了reset事件')
  }
})